package com.kh.statistics.video.helper;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName CookieHelper
 * @Description TODO
 * @Author konghong1
 * @Date 2024/5/10 21:47
 * @Version 1.0
 **/
@Slf4j
public class CookieHelper {
    public static Map<String, String> handlerCookie(String cookie, Map<String, String> headers, String jsonHeader) {

        Map<String, String> map = new HashMap<>();
        if (null == headers && StringUtils.isBlank(cookie) && StringUtils.isBlank(jsonHeader)) {
            return map;
        }
        if (StringUtils.isNotBlank(cookie)) {
            map.put("cookie", cookie);
        }
        if (StringUtils.isNotBlank(jsonHeader)) {
            Map map1 = JSONObject.parseObject(jsonHeader, Map.class);
            Map<String, String> headersMap = new HashMap<>();

            map1.forEach((key, value) -> {
                headersMap.put(String.valueOf(key), String.valueOf(value));
            });
            map.putAll(headersMap);
        }
        if (null != headers) {
            map.putAll(headers);
        }
        return map;
    }

    public static Set<Cookie> getCookies(WebDriver driver, String platform) throws InterruptedException {
        WebDriver.Options manage = driver.manage();
        manage.deleteAllCookies();
        Set<Cookie> cookies = manage.getCookies();
        AtomicInteger atomicInteger = new AtomicInteger(0);
        while (CollectionUtils.isEmpty(cookies) && atomicInteger.get() < 30) {
            cookies = manage.getCookies();
            atomicInteger.incrementAndGet();
            log.info("【{}平台】正在获取cookies,获取此次：{}", platform, atomicInteger.get());
            Thread.sleep(4000);
        }
        return cookies;
    }
}
